package com.cysd.ewmxns.sdw_ui.activity

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import com.cszy.ewmxns.base.BaseVMActivity
import com.cszy.ewmxns.ext.launch
import com.cszy.ewmxns.ext.toast

import com.cysd.ewmxns.sdw_ui.dialog.PermissoTipDialog
import com.cysd.ewmxns.sdw_ui.dialog.Sdw_UserRefusedPermissonDialog
import com.cysd.ewmxns.sdw_ui.fragment.Sdw_IndexFragment
import com.cysd.ewmxns.sdw_ui.fragment.Sdw_QrCodeFragment
import com.cysd.ewmxns.sdw_ui.fragment.Sdw_WodeFragment
import com.cysd.ewmxns.sdw_utils.SpUtils
import com.cysd.ewmxns.sdw_viewmodel.MainViewModel
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans
import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener
import com.hnyyac.ad.mds.manager.AdManager.loadChapin

import qrrspeeelild.rqrc0ode.andro0ild.R
import qrrspeeelild.rqrc0ode.andro0ild.databinding.ActivityMainBinding




class MainActivity : BaseVMActivity<MainViewModel, ActivityMainBinding>(),IAdViewListener {
    private var firstClick: Long = 0
    private var tabshowAd: String? = null // 记录当前点击的 Tab 位置
    private var currentTab = 0
    private val fragments = arrayOfNulls<Fragment>(3)

    private var pernissonTopdialog: PermissoTipDialog? = null

    override fun initView(savedInstanceState: Bundle?) {
        val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)

        // 初始化 Fragment 数组
        fragments[0] = Sdw_IndexFragment()
        fragments[1] = Sdw_QrCodeFragment()
        fragments[2] = Sdw_WodeFragment()

        // 默认显示第一个 Fragment
        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .add(R.id.fragment_container_main, fragments[0]!!, "tab0")
                .commit()
            currentTab = 0
        } else {
            // 恢复Fragment状态
            currentTab = savedInstanceState.getInt("currentTab", 0)
            fragments[0] = supportFragmentManager.findFragmentByTag("tab0") ?: Sdw_IndexFragment()
            fragments[1] = supportFragmentManager.findFragmentByTag("tab1") ?: Sdw_QrCodeFragment()
            fragments[2] = supportFragmentManager.findFragmentByTag("tab2") ?: Sdw_WodeFragment()

            // 显示当前Tab，隐藏其他
            supportFragmentManager.beginTransaction().apply {
                fragments.forEachIndexed { index, fragment ->
                    fragment?.let {
                        if (index == currentTab) {
                            show(it)
                        } else if (it.isAdded) {
                            hide(it)
                        }
                    }
                }
            }.commit()
        }

        bottomNavigationView.setOnNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.navigation_home -> switchTab(0)
                R.id.navigation_saoma -> switchTab(1)
                R.id.navigation_network -> switchTab(2)
            }
            true
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("currentTab", currentTab)
    }

    private fun switchTab(position: Int) {
        if (currentTab == position) return

        val transaction = supportFragmentManager.beginTransaction()

        // 隐藏当前Fragment
        fragments[currentTab]?.let {
            if (it.isAdded) {
                transaction.hide(it)
            }
        }

        // 显示或添加新的Fragment
        fragments[position]?.let { fragment ->
            if (fragment.isAdded) {
                transaction.show(fragment)
            } else {
                transaction.add(R.id.fragment_container_main, fragment, "tab$position")
            }
        }

        transaction.commit()
        currentTab = position

        // 广告相关
        tabshowAd = "tab${position + 1}"
        showADIfNeeded(position)
    }

    override fun initData() {
//        var app_progress=  SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS)
//        if (app_progress=="0")return
       // BaseApplication.instance.startTimer()
    }

    override fun initListener() {
//       mBinding.rvSaoma.setOnClickListener {
//           if (XXPermissions.isGranted(this, android.Manifest.permission.CAMERA)) {
//               // 监听扫描结果
//               var bundle=Bundle()
//               bundle.putString("type","general")
//               launch(bundle,QrcodeActivity::class.java)
//
//           } else {
//               request_Permission(
//                   this,
//                   android.Manifest.permission.CAMERA,
//                   "相机",
//                   "需要获取您的相机权限用来扫描二维码"
//               )
//           }
//       }
    }

    private fun showADIfNeeded(tabPosition: Int) {
        var tab1= SpUtils.getInstance().getBoolean(BaseAppConstans.IS_show_TAB1,false)
        var tab2=SpUtils.getInstance().getBoolean(BaseAppConstans.IS_show_TAB2,false)
        var tab3=SpUtils.getInstance().getBoolean(BaseAppConstans.IS_show_TAB3,false)
        if (tabPosition==0&&!tab1){
            loadAndShowAd(29)
        }
        if (tabPosition==1&&!tab2){
            loadAndShowAd(23)
        }
        if (tabPosition==2&&!tab3){
            loadAndShowAd(23)
        }
    }

    private fun loadAndShowAd(position: Int) {
        loadChapin(
            this,
            position,
            listener = this,
            adLoadListener = object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                    // 处理加载失败
                }
            }
        )
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onAppExit()
            return true
        }
        return false
    }

    private fun onAppExit() {
        if (System.currentTimeMillis() - firstClick > 2000L) {
            firstClick = System.currentTimeMillis()
            toast("再按一次退出应用")
            return
        }
        finish()
    }

    override fun onTrigger(adView: IAdView) {}
    override fun onAdShow(adView: IAdView) {}
    override fun onAdClick(adView: IAdView) {}

    override fun onAdClose(adView: IAdView) {
        when(tabshowAd){
            "tab1"-> SpUtils.getInstance().putBoolean(BaseAppConstans.IS_show_TAB1,true)
            "tab2"-> SpUtils.getInstance().putBoolean(BaseAppConstans.IS_show_TAB2,true)
            "tab3"-> SpUtils.getInstance().putBoolean(BaseAppConstans.IS_show_TAB3,true)
        }
    }

    override fun onError(msg: String) {}
    override fun onLoadError(adView: IAdView) {}
    override fun onSuccess(adView: IAdView) {}
    override fun onLoad(adView: IAdView) {}
    override fun onSkipped() {}
    override fun onNoAd() {}
    override fun onTimeOut() {}

    fun request_Permission(
        context: Activity,
        req_permisson: String,
        permisson_name: String,
        content: String
    ) {
        if (!SpUtils.getInstance().getBoolean(permisson_name)) {
            showPermissonTipsDialog(context, content)
        }
        XXPermissions.with(context)
            .permission(req_permisson)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    pernissonTopdialog?.dismiss()
                    if (!allGranted) {
                        toast("获取 $permisson_name 权限成功")
                        return
                    }
                    SpUtils.getInstance().putBoolean(permisson_name, true)
                    toast("获取 $permisson_name 权限成功")

                    var bundle=Bundle()
                    bundle.putString("type","general")
                    launch(bundle,Sdw_QrcodeActivity::class.java)
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        pernissonTopdialog?.dismiss()
                        showDoNotAskAgainDialog(this@MainActivity, req_permisson, permisson_name)
                    } else {
                        pernissonTopdialog?.dismiss()
                    }
                }
            })
    }

    fun showPermissonTipsDialog(context: Context, content: String) {
        pernissonTopdialog = PermissoTipDialog(context)
        pernissonTopdialog!!.setPermissionMessage(content)
        pernissonTopdialog!!.show()
        pernissonTopdialog!!.setCancelable(false)
    }

    fun showDoNotAskAgainDialog(context: Context, permission: String, permissionName: String) {
        var dialog = Sdw_UserRefusedPermissonDialog(context, permission)
        dialog.setPermissionMessage("您未授予 $permissionName 权限，请去设置中开启")
        dialog.setCancelable(false)
        dialog.show()
    }
}